package logic

import (
	"api/model/discount"
	"api/service"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DiscountListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDiscountListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DiscountListLogic {
	return &DiscountListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DiscountListLogic) DiscountList() (resp *types.ResponseDiscountList, err error) {
	conn := sqlx.NewMysql(l.svcCtx.Config.DataSource)
	businessService := service.NewBusinessService(l.ctx, l.svcCtx)
	business := businessService.GetLoginBusinessInfo()
	discountModel := discount.NewDiscountModel(conn)
	list, err := discountModel.ListByBusId(l.ctx, business.Id)

	if err == nil {
		arr := make([]types.BusDicount, len(*list))

		var d = &types.BusDicount{
			Discount:   0,
			Money:      0,
			BusinessId: 0,
		}

		ids := make([]int64, len(*list))

		for index, item := range *list {
			d.Discount = item.Discount
			d.Money = item.Money
			d.BusinessId = item.BusinessId
			d.Id = item.Id
			d.Sale = 0
			arr[index] = *d

			ids[index] = item.Id

		}

		// 获取销量
		redis := l.svcCtx.RedisPool.Get()
		defer redis.Close()
		salesArr := businessService.GetDiscountSaleListByIds(redis, ids)

		if salesArr != nil {
			for index, item := range arr {
				if _, ok := salesArr[item.Id]; ok {
					arr[index].Sale = salesArr[item.Id]
				}
			}
		}

		resp = &types.ResponseDiscountList{
			Code: 200,
			List: arr,
		}
	} else {
		fmt.Println(err.Error())
		resp = &types.ResponseDiscountList{
			Code: 200,
			List: nil,
		}
	}
	return resp, nil
}
